const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      Manager: [],
      activityType: [
        {
          value: "党员大会",
          label: "党员大会",
        },
        {
          value: "党委会",
          label: "党委会",
        },
        {
          value: "党小组会",
          label: "党小组会",
        },
        {
          value: "党课",
          label: "党课",
        },
        {
          value: "双联系双报道",
          label: "双联系双报道",
        },
        {
          value: "主题党日",
          label: "主题党日",
        },
      ],
      Recorder: [],
      dataForm: { Activity_Points: 1 },
      childDataForm1: [{}],
      childDataForm: [],
      isTree: false,
      tableData: [],
      fileList2: [],
      fileList1: [],
      fileList3: [],
      type:'',
      showDialog:false,
      party_organization_activities_summary:[],
      fileUrl:''
    };
  },
  mounted() {
    let activityType = sessionStorage.getItem("addType");
    // 新增：将获取到的类型设置到数据模型
    if (activityType) {
      this.dataForm.Activity_Type = activityType;
    }
    let ls_URL = window.location.href;
    this.type = getQueryObject(ls_URL, "type");// 获取 nodeKey 参数
    this.getCategory();
  },
  watch: {
    isTree(val) {
      this.changeOrganization([this.dataForm.Party_Organization_SerialNumber])
    }
  },
  computed: {
    Personal_Name() {
      return function (val) {
        let obj = this.Recorder.filter(i => i.ID_Card_Number == val)[0];
        if (obj) {
          return obj.Personal_Name
        } else {
          return '';
        }
      }
    },
    Party_Organization_Name() {
      return function (val) {
        let obj = this.Manager.filter(i => i.Party_Organization_SerialNumber == val)[0];
        if (obj) {
          return obj.Party_Organization_Name
        } else {
          return '';
        }
      }
    }
  },
  methods: {
    config(data) {
      data.forEach(item => {
        if (item.Party_Organization_Type != '支部') {
          item.disabled = true
        }
        if (item.children && item.children.length > 0) {
          this.config(item.children);
        }
      })
    },
    getCategory() {
      // $.ajax({
      //   headers: {
      //     "content-type": "application/x-www-form-urlencoded",
      //   },
      //   url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
      //   method: "post",
      //   data: {
      //     Data: "party_organization", //表名
      //     Condition: "Row_Status='0'  AND Party_Organization_Type='支部'",
      //   },
      //   success: (res) => {
      //     this.Manager = res;
      //   },
      // });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
        type: "GET",
        data: {
          TableName: 'party_organization',
          NodeCode: '',
        },
        success: (data) => {
          this.config(data)
          this.Manager = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: "party_organization", //表名
          Condition: "Row_Status='0'  AND Party_Organization_Type='支部'",
        },
        success: (res) => {
          this.Manager = res;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: "personal_information", //表名
          Condition: "Row_Status='0'",
        },
        success: (res) => {
          this.Recorder = res;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    Organization(data, arr) {
      data.forEach(item => {
        arr.push(item.Party_Organization_SerialNumber);
        if (item.children) {
          this.Organization(item.children, arr);
        }
      })
    },
    preview(row) {
      this.fileUrl = photo + row.Activity_Summary_URL;
      this.showDialog = true;
  },
  async download(row) {
      // if (row.Activity_Summary_URL) {
      //     window.location.href = photo + row.Activity_Summary_URL;
      // }
      let apiUrl = photo + row.Activity_Summary_URL;
      let fileName = apiUrl.split('/').pop();
      try {
        const response = await fetch(apiUrl);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = fileName || 'download';
        document.body.appendChild(a);
        a.click();

        // 清理
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      } catch (error) {
        console.error('下载失败:', error);
      }
  },
    changeOrganization(arr) {
      let val = arr[arr.length - 1]
      if (this.isTree) {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
          type: "GET",
          data: {
            TableName: 'party_organization',
            NodeCode: val
          },
          success: (data) => {
            let arr = [];
            this.Organization(data, arr);
            let str = '';
            [val, ...arr].forEach(item => {
              if (str) {
                str += "\r\nOR party_member_information.Party_Organization_SerialNumber = '" + item + "'"
              } else {
                str = "\r\nparty_member_information.Party_Organization_SerialNumber = '" + item + "'"
              }
            })
            if (str) {
              str = "and (" + str + ")";
              $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                  SQLSerialNumber: "f_party_member_information",
                  Condition: '',
                  ExtensionCondition: window.btoa(unescape(encodeURIComponent(str)))
                },
                success: (res) => {
                  if (this.action == 'Add') {
                    this.childDataForm = res;
                  } else {
                    let childDataForm = this.childDataForm;
                    this.childDataForm.forEach(item => {
                      if (!res.some(i => i.ID_Card_Number == item.ID_Card_Number)) {
                        if (!Object.keys(item).some(i => i.includes('_Original'))) {
                          childDataForm = childDataForm.filter(i => i.ID_Card_Number != item.ID_Card_Number);
                        } else {
                          item.Row_Status = '1'
                        }
                      }
                    })
                    this.childDataForm = childDataForm;
                    res.forEach(item => {
                      let obj = this.childDataForm.filter(i => i.ID_Card_Number == item.ID_Card_Number)[0];
                      if (obj) {
                        obj.Row_Status = '0'
                      } else {
                        this.childDataForm.push(item);
                      }
                    })
                  }
                },
                complete: (XMLHttpRequest) => {
                  requestPretreatment(XMLHttpRequest);
                },
              });
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json",
        });
      } else {
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
          method: "post",
          data: {
            SQLSerialNumber: "f_party_member_information",
            Condition: '',
            ExtensionCondition: window.btoa(unescape(encodeURIComponent("AND party_member_information.Party_Organization_SerialNumber = '" + val + "'")))
          },
          success: (res) => {
            if (this.action == 'Add') {
              this.childDataForm = res;
            } else {
              let childDataForm = this.childDataForm;
              this.childDataForm.forEach(item => {
                if (!res.some(i => i.ID_Card_Number == item.ID_Card_Number)) {
                  if (!Object.keys(item).some(i => i.includes('_Original'))) {
                    childDataForm = childDataForm.filter(i => i.ID_Card_Number != item.ID_Card_Number);
                  } else {
                    item.Row_Status = '1'
                  }
                }
              })
              this.childDataForm = childDataForm;
              res.forEach(item => {
                let obj = this.childDataForm.filter(i => i.ID_Card_Number == item.ID_Card_Number)[0];
                if (obj) {
                  obj.Row_Status = '0'
                } else {
                  this.childDataForm.push(item);
                }
              })
              console.log(this.childDataForm);
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }
    },
    handleRemove(row, index) {
      if (!Object.keys(row).some(item => item.includes('_Original'))) {
        this.childDataForm = this.childDataForm.filter((i, id) => id != index);
      } else {
        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          row.Row_Status = '1'
        }).catch(() => {
        });
      }
    },
    async handleChange({ raw }, type) {
      const result = await uploadBinaryFile(raw);
      if (result.status == 'success') {

        this.party_organization_activities_summary.push({
          Party_Organization_Activity_SerialNumber: this.dataForm.Party_Organization_Activity_SerialNumber,
          Activity_Summary_URL: result.fileName,
          Activity_Summary_Type: type,
          uid: raw.uid,
        })
      }
    },
    handleRemove({ raw }) {
      this.party_organization_activities_summary = this.party_organization_activities_summary.filter(i => i.uid != raw.uid);
    },
    //提交表单
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            if (item.hasAttribute('data-options')) {
              let lJSONObject_ChildData_Options = new Object();
              lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

              let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
              let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
              // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
              if (this[ls_DataForm][ls_primary_key]) {
                this[ls_ChildDataForm].forEach(item => {
                  item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                })
              }
              //建立子表结构体
              let JSONArray_ChildRecord = new Array();
              JSONArray_ChildRecord = this[ls_ChildDataForm];
              if (!this[ls_DataForm].Children) {
                this[ls_DataForm].Children = new Object();
              }
              this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
            }
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(this[ls_DataForm]);
          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          lJSONObject_DataSet[action] = lJSONObject_Table;
        } else if (action == 'Modify') {
          this[ls_DataForm].Activity_isEdit = '2';
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_DataSet[action] = lJSONObject_Table;
          lJSONObject_DataSet['Add'] = new Object();
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        if (!lJSONObject_DataSet['Add']) {
          lJSONObject_DataSet['Add'] = new Object();
        }
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSaveByRequestBody",
          Operation_IP: getIpAddress()
        }]
        submitSave(lJSONObject_DataSet, (res) => {
          if (res.Status == 'success') {
            window.history.go(-1)
            // window.history.go(-1);
          }
          this.loading = false;
        })
        // $.ajax({
        //   headers: requestHeaders("JSON"),
        //   url: `${mh}/generalBusiness/generalSaveByRequestBody`,
        //   method: "post",
        //   data: JSON.stringify({
        //     Data: lJSONObject_DataSet,
        //   }),
        //   success: (res) => {
        //     if (res.Status == 'success') {
        //       window.location.href = './index.html'
        //       // window.history.go(-1);
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     this.loading = false;
        //     requestPretreatment(XMLHttpRequest)
        //   }
        // });
      }
    },
  },

};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
app.component('yl-cascader', ylCascader)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
